package com.moonhill.bt;

import java.io.DataInputStream;

public class DataReader extends Thread {
	private DataInputStream dis;
	private boolean cancel;
	private DataReaderListener listener;

	public DataReader(DataInputStream dis, DataReaderListener listener) {
		this.dis = dis;
		this.listener = listener;
		this.start();
	}

	public void run() {
		while (!cancel) {
			try {
				int msgLen = dis.readInt();
				byte[] data = new byte[msgLen];
				dis.read(data);
				listener.onReceiveData(data);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				listener.onConnectionError(this);
				break;

			}

		}

	}

	public void cancel() {
		this.cancel = true;
		Thread t = new Thread(){
			public void run(){
				try {
					dis.close();
					dis = null;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
		t.start();
	}
}
